import json
import logging

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.common.selenium_manager import logger
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from config import BASE_PATH,init_log_config

class DriverUitls:
    __driver = None

    @classmethod
    def get_driver(cls):
        if cls.__driver is None:
            cls.__driver = webdriver.Chrome(service=Service(r'D:\Python\chromedriver.exe'))
            cls.__driver.maximize_window()
            cls.__driver.implicitly_wait(10)
        return cls.__driver

    @classmethod
    def quit_driver(cls):
        if cls.__driver is not None:
            cls.__driver.quit()
            cls.__driver = None

def get_el_text(driver,xpath_str,wait_text):
    msg = None
    try:
        WebDriverWait(driver,3,1).until(
            EC.text_to_be_present_in_element((By.XPATH,xpath_str),wait_text))
    except Exception as e:
        # print(e)
        logging.error(e)
        driver.get_screenshot_as_file("登陆功能执行失败截图.png")
    finally:
        msg = driver.find_element(By.XPATH,xpath_str).text
        # print("获取判定登陆的文本信息:{}".format(msg))
        logging.info("获取判定登陆的文本信息:{}".format(msg))
    return msg

def el_is_exist_by_text(driver,key_text):
    is_suc = None
    try:
        is_suc = driver.find_element(By.XPATH,
                        "//*[contains(text(),'{}')]".format(key_text))
        logging.info("查找文本{}对应的元素，存在".format(key_text))
    except:
        logging.error("查找文本{}对应的元素，不存在".format(key_text))
        driver.get_screenshot_as_file("查找文本元素失败.png")
    return is_suc

# def get_el_cunzai(driver,xpath_str,wait_text):
#     msg = None
#     try:
#         WebDriverWait(driver, 3, 1).until(
#             EC.text_to_be_present_in_element(
#                 (By.XPATH, xpath_str), wait_text))
#     except Exception as e:
#         # print(e)
#         logging.error(e)
#         # driver.get_screenshot_as_file("登陆功能执行失败截图.png")
#     finally:
#         msg = driver.find_element(By.XPATH, xpath_str).text
#         return msg

def read_json(filename):
    file_path = BASE_PATH + "/data/{}.json".format(filename)
    with open(file_path,encoding="utf-8") as f:
        all_case = json.load(f)
    print("获取原始外部文件测试数据:{}".format(all_case))
    logging.info("获取原始外部文件测试数据:{}".format(all_case))
    case_list = list()
    for case_dict in all_case.values():
        case_tuple = tuple(case_dict.values())
        case_list.append(case_tuple)
    print("获取原始外部文件测试数据:{}".format(case_list))
    logging.info("转化后的测试数据:{}".format(case_list))
    return case_list
if __name__ == '__main__':
    read_json("login_data")